<template>
  <div class="SetupSettingPage page">
    <div class="form-search">
      <div class="search-item">
        <div class="shop-label">商家：</div>
        <el-select v-model="query.shopId" filterable placeholder="请选择商家">
          <el-option v-for="item in state.shopList" :key="item.id" :value="item.shopId" :label="item.shopName">{{
            item.shopName
          }}</el-option>
        </el-select>
      </div>
      <div class="search-item">
        <el-select v-model="query.configType" placeholder="请选择配置分组" clearable>
          <el-option
            v-for="(item, index) in state.configTypeList"
            :key="item.dictName"
            :value="item.dictName"
            :label="item.dictDescribe"
            >{{ item.dictDescribe }}</el-option
          >
        </el-select>
      </div>
      <div class="search-item">
        <el-input v-model="query.configText" placeholder="请输入标题文本" clearable></el-input>
      </div>
      <div class="search-item">
        <el-select v-model="query.formType" placeholder="请选择表单类型" clearable>
          <el-option
            v-for="(item, index) in state.formTypeList"
            :key="item.dictId"
            :value="item.dictName"
            :label="item.dictDescribe"
            >{{ item.dictDescribe }}</el-option
          >
        </el-select>
      </div>
      <div class="search-item">
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>
    <div :key="query.shopId" class="w-full config-wrap" v-loading="state.loading">
      <div class="config-panel" v-for="(group, i) in state.shopConfigList" :key="query.shopId + i">
        <div class="config-title">{{ group[0].configTypeDescribe }}</div>
        <div class="config-item" v-for="item in group" :key="item.shopId + item.id">
          <span class="config-item-title">
            <span class="config-item-title-icon" v-if="item.hasDefault == 1">*</span>
            {{ item.configText }}
          </span>
          <div class="config-item-content">
            <el-input
              v-if="item.formType === 'el-input'"
              v-model="item.configValue"
              @change="(value) => onChange(value, item)"
            ></el-input>
            <el-input-number
              v-if="item.formType === 'el-input-number'"
              v-model="item.configValue"
              @change="(value) => onChange(value, item)"
            ></el-input-number>
            <el-switch
              v-else-if="item.formType === 'el-switch'"
              v-model="item.configValue"
              :inactive-value="item.options[0].value"
              :active-value="item.options[1].value"
              :inactive-text="item.options[0].label"
              :active-text="item.options[1].label"
              @change="(value) => onChange(value, item)"
            />

            <el-select
              v-else-if="item.formType === 'el-select'"
              v-model="item.configValue"
              placeholder="请选择"
              @change="(value) => onChange(value, item)"
            >
              <el-option
                v-for="option in item.options"
                :key="option?.value"
                :label="option?.label"
                :value="option?.value"
                >{{ option?.label }}
              </el-option>
            </el-select>

            <el-select
              v-else-if="item.formType === 'el-select-multiple'"
              v-model="item.configValue"
              placeholder="请选择"
              :multiple="true"
              @change="(value) => onChange(value, item)"
            >
              <el-option
                v-for="option in item.options"
                :key="option?.value"
                :label="option?.label"
                :value="option?.value"
                >{{ option?.label }}
              </el-option>
            </el-select>

            <el-radio-group
              v-else-if="item.formType === 'el-radio'"
              v-model="item.configValue"
              @change="(value) => onChange(value, item)"
            >
              <el-radio
                v-for="option in item.options"
                :key="option?.value"
                :label="option?.label"
                :value="option?.value"
                >{{ option?.label }}
              </el-radio>
            </el-radio-group>

            <el-checkbox-group
              v-else-if="item.formType === 'el-checkbox'"
              v-model="item.configValue"
              @change="(value) => onChange(value, item)"
            >
              <el-checkbox
                v-for="option in item.options"
                :key="option?.value"
                :label="option?.label"
                :value="option?.value"
                >{{ option?.label }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </div>
      <div class="center" v-if="!state.shopConfigList.length">
        <el-empty />
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, onMounted, defineComponent, watch } from 'vue'
import {
  postShopConfigGetAll,
  postShopConfigUpdate,
  getShopConfigGetConfigTypeSelect,
  getShopConfigGetFormTypeSelect,
} from '@/api/shop'
import { businessListGetAll } from '@/api/business'
import { ElMessage } from 'element-plus'
import { getJSONParse } from '@/utils/index'

defineComponent({
  name: 'SetupSetting',
})

const state = reactive({
  shopList: [],
  configTypeList: [],
  formTypeList: [],
  loading: false,
  shopConfigList: [],
})

const query = reactive({
  id: '',
  shopId: '',
  configType: undefined, // 配置类型(参考数据字典SHOP_CONFIG_TYPE)
  configText: undefined, // 配置键对应的展示文本
  formType: undefined, // 表单类型(参考数据字典FORM_TYPE)
})

function onChange(value, item) {
  console.log('change', value, item)
  postShopConfigUpdate({
    shopId: query.shopId,
    configValue: ['el-select-multiple', 'el-checkbox'].includes(item.formType) ? value.toString() : value,
    id: item.id,
    configType: item.configType,
    configModelId: item.configModelId,
    configKey: item.configKey,
    configText: item.configText,
    formType: item.formType,
    formValue: item.formValue,
    hasDefault: item.hasDefault, // is mean isRequired
    hasEditor: item.hasEditor,
  })
    .then((res) => {
      ElMessage.success(`“${item.configTypeDescribe}-${item.configText}”修改成功`)
      console.log(res)
    })
    .catch((err) => {
      console.log(err)
    })
}

function getShopConfigList() {
  state.loading = true
  postShopConfigGetAll({
    page: 1,
    pageSize: 100,
    shopId: query.shopId,
    configType: query.configType || undefined,
    configText: query.configText || undefined,
    formType: query.formType || undefined,
  })
    .then(({ data }) => {
      console.log('config list: ', data)
      const configMap = data.list.reduce((acc, cur) => {
        if (!['el-input', 'el-input-number'].includes(cur.formType)) {
          cur.options = getJSONParse(cur.formValue)
          if (['el-select-multiple', 'el-checkbox'].includes(cur.formType)) {
            cur.configValue = (cur.configValue + '').split(',')
          } else if (typeof cur.options[0].value == 'number') {
            cur.configValue = +cur.configValue
          }
        }
        if (acc[cur.configType]) {
          acc[cur.configType].push(cur)
        } else {
          acc[cur.configType] = [cur]
        }

        return acc
      }, {})
      state.shopConfigList.length = 0
      for (const key in configMap) {
        state.shopConfigList.push(configMap[key])
      }
      console.log('config list: ', state.shopConfigList)
    })
    .finally(() => {
      state.loading = false
    })
}

// function onShopChange(value) {
//   console.log("on shop change: ", value);
//   getShopConfigList();
// }

function getAllShops() {
  businessListGetAll({ page: 1, pageSize: 9999 }).then((res) => {
    state.shopList = res.data.list
    query.shopId = state.shopList[0]?.shopId
  })
}

function handleSearch() {
  getShopConfigList()
}

function handleReset() {
  query.configType = undefined
  query.configText = undefined
  query.formType = undefined
  getShopConfigList()
}

getShopConfigGetConfigTypeSelect({ page: 1, pageSize: 9999 }).then((res) => {
  state.configTypeList = res.data
})
getShopConfigGetFormTypeSelect({ page: 1, pageSize: 9999 }).then((res) => {
  state.formTypeList = res.data
})

watch(
  () => query.shopId,
  (val) => {
    if (val) {
      getShopConfigList()
    }
  },
  {
    immediate: true,
  },
)
onMounted(() => {
  getAllShops()
})
</script>

<style scoped lang="scss">
.page {
  margin-top: 20px;
  padding: 20px;
  background-color: #ffffff;
  .shop-label {
    display: inline-block;
    min-width: 3em;
    font-weight: bold;
    text-align: right;
    margin-right: 8px;
  }
  .config-panel {
    width: 50%;
    .config-title {
      color: #333;
      font-size: 16px;
      font-weight: bold;
    }
    .config-item {
      margin-top: 10px;
      .config-item-title {
        display: inline-block;
        width: 200px;
        text-align: right;
        margin-right: 16px;
      }
      .config-item-title-icon {
        color: #f56c6c;
      }
      .config-item-content {
        display: inline-block;
        width: calc(100% - 200px);
        max-width: 200px;
      }
    }
  }
  .center {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
  }
  .config-wrap {
    display: flex;
    flex-wrap: wrap;
  }
}
</style>
